/***********************按键****************************
*******************************************************/
module Key4x4(  input clk,               //   100 MHz
						inout  [3:0]KEY_H,//4x4矩阵键盘
						inout  [3:0]KEY_L,
						//Avalon
						input            rst_n,
						input 				select_n,
						input            rd_n,
						output reg [7:0] readdata,
						output reg        irq   //高电平促发中断
						);


//reg [10:0]KEYFormer;
//矩阵键盘
reg [31:0] ADD0;
always @(posedge clk,negedge rst_n) begin 
	if(!rst_n)  
		ADD0<=0;
	else 
		ADD0<=ADD0+32'd42946;
end 


wire clk1=ADD0[31];  //1k 

reg i;
reg [3:0]rKEY_H,rKEY_L;
always @(posedge clk1)begin
  i<=~i;
  rKEY_H<=KEY_H;
  rKEY_L<=KEY_L;
end

reg [7:0]keyvalue;
always @(posedge clk1)
 case(i)
 1'b1:keyvalue[7:4]<=~rKEY_H;
 1'b0:keyvalue[3:0]<=~rKEY_L;
 endcase 
assign KEY_H=i?4'h0:4'hz;
assign KEY_L=!i?4'h0:4'hz;

reg key_interrupt;

always @(posedge clk1)
key_interrupt=(keyvalue[7:4]&&keyvalue[3:0]);

reg [2:0] state_now,state_next;
always @(posedge  clk1,negedge rst_n) begin 
	if(!rst_n) 
		state_now<=3'd0;
	else state_now<=state_next;
end 

always @(*) begin 
	case(state_now) 
	3'd0: if(key_interrupt) state_next=3'd1;
	else state_next=3'd0;
	3'd1: state_next=3'd2;
	3'd2:  if(key_interrupt) state_next=3'd3;
		else state_next=3'd0;
	3'd3: state_next=3'd4;
	3'd4: if(t_delay>500) 
				state_next=3'd5;
			else state_next=3'd4;
	3'd5:  state_next=3'd0;
	endcase 
end 

reg [10:0] t_delay;
always @(posedge clk1,negedge rst_n) begin 
	if(!rst_n) begin 
		t_delay<=0;
	end 
	else if(state_now==3'd4) 
		t_delay<=t_delay+1'b1;
	else 
		t_delay<=0;
end 

reg [7:0] KeyValue_Reg;
always @(posedge clk,negedge rst_n) begin 
	if(!rst_n ) begin 
		KeyValue_Reg<=0;
		irq<=0;
	end 
	else if(state_now==3'd3) begin 
		KeyValue_Reg<=keyvalue;
		irq<=1;
	end 
	else begin 
		KeyValue_Reg<=KeyValue_Reg;
		irq<=0;
	end 
end 



always @(posedge clk,negedge rst_n) begin 
	if(!rst_n) begin 
		readdata<=0;
	end 
	else if((!select_n) &&(!rd_n) ) 
		readdata<=KeyValue_Reg;
end 


		
			
endmodule		
				